import {createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw, useRoute} from 'vue-router'
import App from "@/App.vue";
import useUserStore from "@/store/modules/user";
import {getQueryObject} from "@/utils/index";
import LoginIndex from "@/views/doctor/loginIndex.vue";
import ClientIndex from "@/views/doctor/ClientIndex.vue";
import StorageUtils from "@/utils/StorageUtils";
import EmployeeScheduleSetting from "@/views/doctor/EmployeeScheduleSettingSelect.vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Doctor',
    component: App,
    redirect: {name: 'DoctorClient'},
    children: [
      {
        path: 'login',
        name: 'DoctorLogin',
        component: LoginIndex,
      },{
        path: 'client',
        name: 'DoctorClient',
        component: App,
        redirect: {name: 'DoctorHome'},
        beforeEnter: (to, from,next) => {
          // 当前登录用户信息
          const userStore = useUserStore()
          if (!userStore.id) {
            Promise.all([userStore.getInfo()]).then(() => {
              next()
            })
          } else {
            next()
          }
        },
        children: [
          {
            path: 'home',
            name: 'DoctorHome',
            component: ClientIndex,
          }, {
            path: 'schedule',
            name: 'DoctorScheduleSetting',
            component: EmployeeScheduleSetting
          }
        ]
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  console.log('---------------------------')
  const params = getQueryObject()
  if (params?.token) {
    StorageUtils.setUserLoginTokenStorage(params.token as string)
  }
  const token = StorageUtils.getUserLoginToken();
  if (to.name != 'DoctorLogin' && !token) {
    next({ name: 'DoctorLogin' })
  }
  else next();
})

export default router
